package com.ys.util.dhecp;

import java.io.*;

import org.csource.common.NameValuePair;
import org.csource.fastdfs.ClientGlobal;
import org.csource.fastdfs.StorageClient1;
import org.csource.fastdfs.StorageServer;
import org.csource.fastdfs.TrackerClient;
import org.csource.fastdfs.TrackerServer;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.multipart.MultipartFile;

import com.ys.util.dhecp.exception.FileNameLengthLimitExceededException;

/**
 * fastDFS文件上传工具类
 * 
 * @author lwl
 */
public class FastDFSUtil {

    private static Logger logger = LoggerFactory.getLogger(FastDFSUtil.class);

	/**
     * 根据文件路径上传
     *
     * @param file 上传的文件包括路径
     * @return 文件名称
     * @throws IOException
     */
	public static final String upload(MultipartFile file) throws IOException{
        try {
            int fileNamelength = file.getOriginalFilename().length();
            if (fileNamelength > FileUploadUtils.DEFAULT_FILE_NAME_LENGTH)
            {
                throw new FileNameLengthLimitExceededException(FileUploadUtils.DEFAULT_FILE_NAME_LENGTH);
            }

            FileUploadUtils.assertAllowed(file, MimeTypeUtils.DEFAULT_ALLOWED_EXTENSION);

        	String originalFilename = file.getOriginalFilename();//获取文件名
            String extName = originalFilename.substring(originalFilename.lastIndexOf(".") + 1);//得到扩展名
            //long startTime=System.currentTimeMillis();
            //加载fastDFS客户端的配置文件
            ClientGlobal.initByProperties("fastdfs/fastdfs.properties");
            //创建tracker的客户端
            TrackerClient tracker = new TrackerClient();
            TrackerServer trackerServer = tracker.getConnection();
            StorageServer storageServer = null;
            //定义storage的客户端
            StorageClient1 client = new StorageClient1(trackerServer, storageServer);
            //文件元信息
            NameValuePair[] metaList = new NameValuePair[1];
            metaList[0] = new NameValuePair("fileName", originalFilename);
            //执行上传
            String pathFileName = client.upload_file1(file.getBytes(), extName, metaList);
            trackerServer.close();
            return pathFileName;
        } catch (Exception ex) {
            logger.error("FastDFSUtil工具类方法upload出错，错误为：" + ex.getMessage());
            return new String("上传失败！");
        }
    }

	/**
     * 下载指定文件
     * 
     * @param filePath 文件路径
     * @param fileName 文件名
     * @param fileType 文件类型
     * @return
     */
	public static void download(String filePath, OutputStream os) throws IOException{
        try {
            //long startTime=System.currentTimeMillis();
            //加载fastDFS客户端的配置文件
            ClientGlobal.initByProperties("fastdfs/fastdfs.properties");

            //创建tracker的客户端
            TrackerClient tracker = new TrackerClient();
            TrackerServer trackerServer = tracker.getConnection();
            StorageServer storageServer = null;
            //定义storage的客户端
            StorageClient1 client = new StorageClient1(trackerServer, storageServer);
            byte[] bytes = client.download_file1(filePath);
            InputStream input = new ByteArrayInputStream(bytes);
            byte[] b = new byte[1024];
            int length;
            while ((length = input.read(b)) > 0)
            {
                os.write(b, 0, length);
            }
            os.close();
            trackerServer.close();
        } catch (Exception ex) {
            logger.error("FastDFSUtil工具类方法download出错，错误为：" + ex.getMessage());
        }
    }
	
	
	/**
     * 删除指定文件
     * 
     * @param filePath 文件路径
     * @return
     */
	public static void delete(String filePath){
        try {
        	
            //加载fastDFS客户端的配置 文件
            ClientGlobal.initByProperties("fastdfs/fastdfs.properties");

            //创建tracker的客户端
            TrackerClient tracker = new TrackerClient();
            TrackerServer trackerServer = tracker.getConnection();
            StorageServer storageServer = null;
            //定义storage的客户端
            StorageClient1 client = new StorageClient1(trackerServer, storageServer);
            
            String groupName=filePath.substring(0, 6);
            String removeName=filePath.substring(7);
            client.delete_file(groupName,removeName);
              //关闭trackerServer的连接
            trackerServer.close();
        } catch (Exception ex) {
            logger.error("FastDFSUtil工具类方法delete出错，错误为：" + ex.getMessage());
        }
    }
	
}
